package com.demo.security.sign;

import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;

import com.demo.security.Base64Util;

/**
 * 数字签名工具类
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/17 13:36
 */
public class SignUtil {

    /**
     * 签名
     * @param content
     * @param privateKey
     * @param type
     * @return
     * @throws Exception
     */
    public static byte[] sign(byte[] content, PrivateKey privateKey,String type) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance(type);
        byte[] bytes = messageDigest.digest(content);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE,privateKey);
        byte[] encryptBytes = cipher.doFinal(bytes);
        return encryptBytes;
    }

    /**
     * 校验
     * @param content
     * @param sign
     * @param publicKey
     * @param type
     * @return
     * @throws Exception
     */
    public static boolean validate(byte[] content, byte[] sign, PublicKey publicKey,String type) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance(type);
        byte[] bytes = messageDigest.digest(content);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE,publicKey);
        byte[] decryptBytes = cipher.doFinal(sign);
        if(Base64Util.byte2base64(decryptBytes).equals(Base64Util.byte2base64(bytes))){
            return true;
        }
        return false;
    }
}
